<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <p class="cont"></p>
    <h1>新用户注册</h1>
    <form>
        <p>手机号： <input type="text" class="tel"></p>
        <p>真实姓名 <input type="text" class="truename"></p>
        <p>密码 <input type="text" class="password"></p>
        <p><button>立即注册</button></p>
        <p class="result"></p>
    </form>
    <script>
        var btn = document.querySelector("button")
        var tel = document.querySelector(".tel")
        var truename = document.querySelector(".truename")
        var password = document.querySelector(".password")
        var result = document.querySelector(".result")
        var cont = document.querySelector(".cont")

        btn.onclick = function(e) {
            btn.innerHTML = "loading";
            e.preventDefault();
            var nameVal = truename.value;
            var telVal = tel.value;
            var pwVal = password.value;

            var xhr = new XMLHttpRequest();
            xhr.open('get', `./insert.php?name=${nameVal}&tel=${telVal}&pw=${pwVal}`, true);
            xhr.send();

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var data = JSON.parse(xhr.responseText);
                    if (data.code == 0) {
                        result.innerHTML = "插入成功";
                    } else {
                        result.innerHTML = "插入失败";
                    }
                    btn.innerHTML = "立即注册";
                    truename.value = '';
                    tel.value = '';
                    password.value = '';
                }
            }
        }
    </script>
</body>

</html>